package org.taobao.ibatiside.ui.action;

import java.sql.SQLException;

import org.apache.commons.lang.StringUtils;
import org.eclipse.datatools.connectivity.IConnectionProfile;
import org.eclipse.datatools.connectivity.sqm.core.rte.ICatalogObject;
import org.eclipse.datatools.modelbase.sql.schema.helper.SQLObjectNameHelper;
import org.eclipse.datatools.modelbase.sql.tables.Table;
import org.eclipse.datatools.sqltools.sql.util.ModelUtil;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.taobao.ibatiside.db.DTPFacadeImpl;
import org.taobao.ibatiside.db.IDTPFacade;
import org.taobao.ibatiside.ui.wizard.DseWizard;

public abstract class DseViewerAction extends AbstractViewerAction {
	protected final IDTPFacade dtpFacade;
	protected final SQLObjectNameHelper nameHelper;
	public DseViewerAction() {
		super();
		dtpFacade = new DTPFacadeImpl();
		nameHelper = new SQLObjectNameHelper();
	}
	protected Table getSelectedElement() {
		IStructuredSelection ss = (IStructuredSelection) event.getSelection();
		return !ss.isEmpty() && (ss.getFirstElement() instanceof Table) ? (Table) ss
				.getFirstElement() : null;
	}
	protected String sampleSQL() {
		return "";
	}

	protected String beauty(String originalSql) {
		if (StringUtils.isBlank(originalSql))
			return "";
		StringBuffer buffer = new StringBuffer(originalSql);
		return buffer.toString();
	}

	@Override
	public void run() {
		DseWizard wizard = new DseWizard();
		Table table = getSelectedElement();
		IConnectionProfile icp = ModelUtil.getConnectionProfile(((ICatalogObject)table).getCatalogDatabase());
		try {
			nameHelper.setIdentifierQuoteString(((ICatalogObject)table).getConnection().getMetaData().getIdentifierQuoteString());
		} catch (SQLException e) {
			nameHelper.setIdentifierQuoteString(dtpFacade.getIdentifierQuoteString(icp));
		}
		assert (icp!=null);
		wizard.getModel().setConnectionProfile(icp);
		wizard.getModel().setOpSql(beauty(sampleSQL()));
		wizard.setWindowTitle("Create iBATIS statement from database");
		WizardDialog dialog = new WizardDialog(viewer.getControl().getShell(),
				wizard);
		dialog.setPageSize(700,600);
		if (dialog.open() == WizardDialog.OK) {
			postWizard(wizard);
		}
	}

	protected void postWizard(DseWizard wizard) {
		// refresh resources affected by wizard.

	}

}
